﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using SCM.API.Read.Application.Command.Purchase;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Interface;
using System.Text;

namespace SCM.API.Read.Application.Handler.Purchase
{
    public class GetPurchaseOneHandler : IRequestHandler<GetPurchaseOneCommand, APIResult<PurchaseManagementModel>>
    {
        IDatabaseContext db;

        public GetPurchaseOneHandler(IDatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<PurchaseManagementModel>> Handle(GetPurchaseOneCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<PurchaseManagementModel>();

            var sqlBuilder = new StringBuilder();

            sqlBuilder.Append(@"SELECT 
                                        id,
                                        ProductName,
                                        purchaseId,
                                        productId,
                                        productSpecs,
                                        unitId,
                                        price,        
                                        num,
                                        total,
                                        OrderType,
                                        vendorId,
                                        vendorName,
                                        ContactPerson,
                                        Phone,
                                        Description,
                                        state,
                                        recorded,
                                        refund,
                                        madeName,
                                        madeTime,
                                        createTime,
                                        updateName,
                                        createName,
                                        isDel,
                                        LocationId,
                                        Bacth
                                FROM PurchaseManagementModel WHERE IsDel=0 ");

            var parameters = new DynamicParameters();

            if (request.ProductId != null)
            {
                sqlBuilder.Append("AND ProductId = @ProductId ");
                parameters.Add("ProductId", request.ProductId);
              
            }

           

            var data = await db.DapperConnection.QueryAsync<PurchaseManagementModel>(sqlBuilder.ToString(), parameters);
           
            result.Msg = "显示成功";
            result.Code = APIEnum.Success;
            result.Data = data.First();
           
            return result;
        }
    }
}
